package com.hndzyu.yd.task;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.gyf.barlibrary.ImmersionBar;
import com.hndzyu.yd.BuildConfig;
import com.hndzyu.yd.R;
import com.hndzyu.yd.bean.UserBean;
import com.hndzyu.yd.pay.PayVIPActivity;
import com.hndzyu.yd.ui.LoginActivity;
import com.hndzyu.yd.url.Path;
import com.hndzyu.yd.utils.OkHttpDownloadJsonUtil;
import com.hndzyu.yd.utils.PhotoUtils;
import com.hndzyu.yd.widget.VipDIalog;

import java.io.File;
import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

/**
 * Created by zz9527 on 2018/10/19.
 */
public class WebActivity extends Activity {
    private WebView web;
    private ValueCallback<Uri> mUploadMessage;
    private ValueCallback<Uri[]> mUploadCallbackAboveL;
    private final static int PHOTO_REQUEST = 100;
    private final static int VIDEO_REQUEST = 120;
    private final static String url = "your_url";
    private boolean videoFlag = false;
    private ProgressBar pg1;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
        ImmersionBar.with(this).statusBarColor(R.color.them).fitsSystemWindows(true).init();
        findViewById(R.id.backarea).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        TextView title = findViewById(R.id.web_title);
        web = findViewById(R.id.web);
        pg1 = findViewById(R.id.progressBar);
        web.setBackgroundColor(0);
        WebSettings settings = web.getSettings();
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setDomStorageEnabled(true);
        settings.setDefaultTextEncodingName("UTF-8");
        settings.setAllowContentAccess(true); // 是否可访问Content Provider的资源，默认值 true
        settings.setAllowFileAccess(true);    // 是否可访问本地文件，默认值 true
        // 是否允许通过file url加载的Javascript读取本地文件，默认值 false
        settings.setAllowFileAccessFromFileURLs(false);
        // 是否允许通过file url加载的Javascript读取全部资源(包括文件,http,https)，默认值 false
        settings.setAllowUniversalAccessFromFileURLs(false);
        //开启JavaScript支持
        settings.setJavaScriptEnabled(true);
        // 支持缩放
        settings.setSupportZoom(true);
        //辅助WebView设置处理关于页面跳转，页面请求等操作
        web.setWebViewClient(new MyWebViewClient());
        //辅助WebView处理图片上传操作
        web.setWebChromeClient(new MyChromeWebClient());


        LinearLayout share=findViewById(R.id.share);
        LinearLayout sharewx = findViewById(R.id.share_wx);
        LinearLayout sharepyq = findViewById(R.id.share_pyq);
        TextView fen = findViewById(R.id.fen);
        int isshow = getIntent().getIntExtra("isshow", 0);
        if (!"".equals(getIntent().getStringExtra("fen"))) {
            if (isshow==0){
                web.getSettings().setTextSize(WebSettings.TextSize.LARGEST);
                web.loadDataWithBaseURL(null, getIntent().getStringExtra("scon"), "text/html", "utf-8", null);
            }else {
                web.loadUrl(getIntent().getStringExtra("url"));
            }
            fen.setText(Html.fromHtml("已获得<font color='#ff0000'>" + getIntent().getStringExtra("fen") + "元</font>"));
        }else {
            title.setText("任务");
            share.setVisibility(View.GONE);
            web.loadUrl(getIntent().getStringExtra("url"));
        }
        sharewx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (UserBean.uid == 0) {
                    startActivity(new Intent(WebActivity.this, LoginActivity.class));
                } else {
                    Wechat.ShareParams sp = new Wechat.ShareParams();
                    sp.setTitle(getIntent().getStringExtra("title"));
                    sp.setText(getIntent().getStringExtra("intro"));
                    sp.setUrl(Path.SHAREURL(getIntent().getStringExtra("ym"),UserBean.uid, getIntent().getIntExtra("shid", 0)));
                    Log.i("__________",Path.SHAREURL(getIntent().getStringExtra("ym"),UserBean.uid, getIntent().getIntExtra("shid", 0)));
                    sp.setImageUrl(Path.img(getIntent().getStringExtra("img")));
                    sp.setShareType(Platform.SHARE_WEBPAGE);
                    Platform weChat = ShareSDK.getPlatform(Wechat.NAME);
//                    weChat.setPlatformActionListener(new PlatformActionListener() {
//                        @Override
//                        public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
//                            //分享成功的回调
//                            Toast.makeText(WebActivity.this, "分享成功", Toast.LENGTH_SHORT).show();
//                        }
//
//                        @Override
//                        public void onError(Platform platform, int i, Throwable throwable) {
//                            Toast.makeText(WebActivity.this, "分享异常", Toast.LENGTH_SHORT).show();
//                        }
//
//                        @Override
//                        public void onCancel(Platform platform, int i) {
//                            Toast.makeText(WebActivity.this, "分享取消", Toast.LENGTH_SHORT).show();
//                        }
//                    });
                    if (getIntent().getIntExtra("type", 0) == 1) {
                        if (UserBean.level > 0) {
                            weChat.share(sp);
                            OkHttpDownloadJsonUtil.downloadJson(WebActivity.this, Path.SHARECALLBACK(UserBean.uid, getIntent().getIntExtra("shid", 0)), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
                                @Override
                                public void onsendJson(String json) {

                                }
                            });
                        } else {
                            final VipDIalog vipDIalog = new VipDIalog(WebActivity.this);
                            vipDIalog.setVIPListener(new VipDIalog.VIPListener() {
                                @Override
                                public void chooseTrue() {
                                    if (UserBean.gao > 0) {
                                        startActivity(new Intent(WebActivity.this, PayVIPActivity.class));
                                    } else {
                                        Toast.makeText(WebActivity.this, "首次提现方能开通", Toast.LENGTH_SHORT).show();
                                    }
                                    vipDIalog.dismiss();
                                }

                                @Override
                                public void chooseFalse() {
                                    vipDIalog.dismiss();

                                }
                            });
                            vipDIalog.show();
                            vipDIalog.setContent();
                        }
                    } else {
                        weChat.share(sp);
                        OkHttpDownloadJsonUtil.downloadJson(WebActivity.this, Path.SHARECALLBACK(UserBean.uid, getIntent().getIntExtra("shid", 0)), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
                            @Override
                            public void onsendJson(String json) {

                            }
                        });
                    }

                }
            }
        });
        sharepyq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (UserBean.uid == 0) {
                    startActivity(new Intent(WebActivity.this, LoginActivity.class));
                } else {
                    WechatMoments.ShareParams sp = new WechatMoments.ShareParams();
                    sp.setTitle(getIntent().getStringExtra("title"));
                    sp.setText("亿点平台，一个用手机赚钱的App");
                    sp.setUrl(Path.SHAREURL(getIntent().getStringExtra("ym"),UserBean.uid, getIntent().getIntExtra("shid", 0)));
                    sp.setShareType(Platform.SHARE_WEBPAGE);
                    Platform weChatMoments = ShareSDK.getPlatform(WechatMoments.NAME);
//                    weChat.setPlatformActionListener(new PlatformActionListener() {
//                        @Override
//                        public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
//                            //分享成功的回调
//                            Toast.makeText(WebActivity.this, "分享成功", Toast.LENGTH_SHORT).show();
//                        }
//
//                        @Override
//                        public void onError(Platform platform, int i, Throwable throwable) {
//                            Toast.makeText(WebActivity.this, "分享异常", Toast.LENGTH_SHORT).show();
//                        }
//
//                        @Override
//                        public void onCancel(Platform platform, int i) {
//                            Toast.makeText(WebActivity.this, "分享取消", Toast.LENGTH_SHORT).show();
//                        }
//                    });
                    if (getIntent().getIntExtra("type", 0) == 1) {
                        if (UserBean.level > 0) {
                            weChatMoments.share(sp);
                            OkHttpDownloadJsonUtil.downloadJson(WebActivity.this, Path.SHARECALLBACK(UserBean.uid, getIntent().getIntExtra("shid", 0)), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
                                @Override
                                public void onsendJson(String json) {

                                }
                            });
                        } else {
                            final VipDIalog vipDIalog = new VipDIalog(WebActivity.this);
                            vipDIalog.setVIPListener(new VipDIalog.VIPListener() {
                                @Override
                                public void chooseTrue() {
                                    if (UserBean.gao > 0) {
                                        startActivity(new Intent(WebActivity.this, PayVIPActivity.class));
                                    } else {
                                        Toast.makeText(WebActivity.this, "首次提现方能开通", Toast.LENGTH_SHORT).show();
                                    }
                                    vipDIalog.dismiss();
                                }

                                @Override
                                public void chooseFalse() {
                                    vipDIalog.dismiss();

                                }
                            });
                            vipDIalog.show();
                            vipDIalog.setContent();
                        }
                    } else {
                        weChatMoments.share(sp);
                        OkHttpDownloadJsonUtil.downloadJson(WebActivity.this, Path.SHARECALLBACK(UserBean.uid, getIntent().getIntExtra("shid", 0)), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
                            @Override
                            public void onsendJson(String json) {

                            }
                        });
                    }

                }
            }
        });
    }




    private void showShare(String platform) {
        final OnekeyShare oks = new OnekeyShare();
        //指定分享的平台，如果为空，还是会调用九宫格的平台列表界面
        if (platform != null) {
            oks.setPlatform(platform);
        }
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle(getIntent().getStringExtra("title"));
//        // titleUrl是标题的网络链接，仅在Linked-in,QQ和QQ空间使用
//        oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("亿点平台,一个能赚钱的手机App");
        //分享网络图片，新浪微博分享网络图片需要通过审核后申请高级写入接口，否则请注释掉测试新浪微博
        oks.setImageUrl(Path.img(getIntent().getStringExtra("img")));
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl(getIntent().getStringExtra("url"));
//        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
//        oks.setComment("我是测试评论文本");
//        // site是分享此内容的网站名称，仅在QQ空间使用
//        oks.setSite("ShareSDK");
//        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
//        oks.setSiteUrl("http://sharesdk.cn");
        oks.setCallback(new PlatformActionListener() {
            @Override
            public void onError(Platform arg0, int arg1, Throwable arg2) {
                //失败的回调，arg:平台对象，arg1:表示当前的动作，arg2:异常信息
                Toast.makeText(WebActivity.this, "分享异常", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onComplete(Platform arg0, int arg1, HashMap arg2) {
                //分享成功的回调
                Toast.makeText(WebActivity.this, "分享成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel(Platform arg0, int arg1) {
                //取消分享的回调
                Toast.makeText(WebActivity.this, "分享取消", Toast.LENGTH_SHORT).show();
            }
        });
        //启动分享
        oks.show(this);
    }


    //自定义 WebViewClient 辅助WebView设置处理关于页面跳转，页面请求等操作【处理tel协议和视频通讯请求url的拦截转发】
    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (!TextUtils.isEmpty(url)) {
                videoFlag = url.contains("vedio");
            }
            if (url.trim().startsWith("tel")) {//特殊情况tel，调用系统的拨号软件拨号【<a href="tel:1111111111">1111111111</a>】
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setData(Uri.parse(url));
                startActivity(i);
            } else {
                String port = url.substring(url.lastIndexOf(":") + 1, url.lastIndexOf("/"));//尝试要拦截的视频通讯url格式(808端口)：【http://xxxx:808/?roomName】
                if (port.equals("808")) {//特殊情况【若打开的链接是视频通讯地址格式则调用系统浏览器打开】
                    Intent i = new Intent(Intent.ACTION_VIEW);
                    i.setData(Uri.parse(url));
                    startActivity(i);
                } else {//其它非特殊情况全部放行
                    view.loadUrl(url);
                }
            }
            return true;
        }
    }


    private Uri imageUri;

    //自定义 WebChromeClient 辅助WebView处理图片上传操作【<input type=file> 文件上传标签】
    public class MyChromeWebClient extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            if (newProgress == 100) {
                pg1.setVisibility(View.GONE);//加载完网页进度条消失
            } else {
                pg1.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                pg1.setProgress(newProgress);//设置进度值
            }
        }

        // For Android 3.0-
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            mUploadMessage = uploadMsg;
            if (videoFlag) {
                recordVideo();
            } else {
                takePhoto();
            }

        }

        // For Android 3.0+
        public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
            mUploadMessage = uploadMsg;
            if (videoFlag) {
                recordVideo();
            } else {
                takePhoto();
            }
        }

        //For Android 4.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            mUploadMessage = uploadMsg;
            if (videoFlag) {
                recordVideo();
            } else {
                takePhoto();
            }
        }

        // For Android 5.0+
        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            mUploadCallbackAboveL = filePathCallback;
            if (videoFlag) {
                recordVideo();
            } else {
                takePhoto();
            }
            return true;
        }
    }

    /**
     * 拍照
     */
    private void takePhoto() {
//        File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/" + SystemClock.currentThreadTimeMillis() + ".jpg");
//        imageUri = Uri.fromFile(fileUri);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
////            Log.i("_________",getPackageName() + ".fileprovider");
//            imageUri = FileProvider.getUriForFile(WebActivity.this, BuildConfig.APPLICATION_ID + ".fileprovider", fileUri);//通过FileProvider创建一个content类型的Uri
//        }
        PhotoUtils.openPic(WebActivity.this,  PHOTO_REQUEST);
    }

    /**
     * 录像
     */
    private void recordVideo() {
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        //限制时长
        intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);
        //开启摄像机
        startActivityForResult(intent, VIDEO_REQUEST);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //如果按下的是回退键且历史记录里确实还有页面
        if ((keyCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()) {
            web.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PHOTO_REQUEST) {
            if (null == mUploadMessage && null == mUploadCallbackAboveL) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (mUploadCallbackAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (mUploadMessage != null) {
                mUploadMessage.onReceiveValue(result);
                mUploadMessage = null;
            }
        } else if (requestCode == VIDEO_REQUEST) {
            if (null == mUploadMessage && null == mUploadCallbackAboveL) return;

            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (mUploadCallbackAboveL != null) {
                if (resultCode == RESULT_OK) {
                    mUploadCallbackAboveL.onReceiveValue(new Uri[]{result});
                    mUploadCallbackAboveL = null;
                } else {
                    mUploadCallbackAboveL.onReceiveValue(new Uri[]{});
                    mUploadCallbackAboveL = null;
                }

            } else if (mUploadMessage != null) {
                if (resultCode == RESULT_OK) {
                    mUploadMessage.onReceiveValue(result);
                    mUploadMessage = null;
                } else {
                    mUploadMessage.onReceiveValue(Uri.EMPTY);
                    mUploadMessage = null;
                }

            }
        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
        if (requestCode != PHOTO_REQUEST || mUploadCallbackAboveL == null) {
            return;
        }
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (data == null) {
//                results = new Uri[]{imageUri};
            } else {
                String dataString = data.getDataString();
                ClipData clipData = data.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }

                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        mUploadCallbackAboveL.onReceiveValue(results);
        mUploadCallbackAboveL = null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ImmersionBar.with(this).destroy();
        if (web != null) {
            web.setWebViewClient(null);
            web.setWebChromeClient(null);
            web.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            web.clearHistory();
//            ((ViewGroup) webView.getParent()).removeView(webView);
            web.destroy();
            web = null;
        }
    }
}
